<template>
  <div class="srceen-wrapper">
    <div class="nav-bar">
      <i class="nav-icon iconfont icon-back" @click="handleBack"></i>
    </div>
    <div id="container" class="container">
    </div>
    <div class="query-bar">

      <a-button @click="showTrade = !showTrade" v-has="'map:biz:data'" :type="showTrade ? 'primary' : 'dashed'" style="margin-left:20px;">
        {{$t('businessData')}}
      </a-button>

      <a-button @click="showTrendStats = !showTrendStats" v-has="'map:biz:trend'" :type="showTrendStats ? 'primary' : 'dashed'"
        style="margin-left:20px;">
        经营趋势
      </a-button>

      <a-button @click="showVehiceInfoOpt = !showVehiceInfoOpt" v-has="'map:ebike:info'" :type="showVehiceInfoOpt ? 'primary' : 'dashed'"
        style="margin-left:20px;">
        {{$t('ebikeInfo')}}
      </a-button>
    </div>

    <track-component ref="modalForm" :visible="showTrackComponent" :carCode="selectedCarCode" :titleCar="titleCar"
      :plate="plate" :currentlongitude="currentlongitude" :currentlatitude="currentlatitude" @ok="modalFormOk"
      @cancel="modalFormCancel"></track-component>
    <div v-show="showTrendStats" v-draggable class="trend-stats-card">
      <a-card :loading="loading" hoverable title="经营趋势">
        <!-- <BizTrends></BizTrends> -->
      </a-card>
    </div>

    <div v-has="'map:biz:data'" v-show="showTrade" v-draggable class="trade-card" style="top: calc(50% - 60px);">
      <div class="trade-card__title">
        <span>收益金额</span>
      </div>
      <div class="trade-card__total">
        <!-- <span class="trade-card__total_num">{{ moneyInfo.statsTotalNum }}</span> -->
        <span class="trade-card__total_num">{{ 208764 }}</span>
        <span class="trade-card__total_unit">元</span>
      </div>
      <div class="trade-card__info">
        <span class="trade-card__info_name">昨</span>
        <!-- <span class="trade-card__info_num">{{moneyInfo.statsNewNum}}</span> -->
        <span class="trade-card__info_num">1054</span>
        <span class="trade-card__info_unit">元</span>
      </div>


    </div>

    <div v-has="'map:biz:data'" v-show="showTrade" v-draggable class="trade-card" style="top: calc(50% + 60px);">
      <div class="trade-card__title">
        <span>支付订单</span>
      </div>
      <div class="trade-card__total">
        <!-- <span class="trade-card__total_num">{{orderInfo.statsTotalNum}}</span> -->
        <span class="trade-card__total_num">4613</span>
        <span class="trade-card__total_unit">笔</span>
      </div>
      <div class="trade-card__info">
        <span class="trade-card__info_name">昨</span>
        <!-- <span class="trade-card__info_num">{{orderInfo.statsNewNum}}</span> -->
        <span class="trade-card__info_num">23</span>
        <span class="trade-card__info_unit">笔</span>
      </div>
    </div>

    <div v-show="showVehiceInfoOpt" v-draggable class="vehicleinfo-opt-card">
      <span>{{$t('ebikeInfo')}}</span>
      <a-checkbox-group :value="vehiceInfoShowValues" @change="onChangeShowValues">
        <a-row>
          <a-col :span="8">
            <a-checkbox value="rpow">
              {{$t('powerkwh')}}
            </a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="rpowCap">
              {{$t('powerper')}}
            </a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="voltage">
              {{$t('voltage')}}
            </a-checkbox>
          </a-col>
          <a-col :span="8">
            <a-checkbox value="current">
              {{$t('electricCurrent')}}
            </a-checkbox>
          </a-col>
          <!-- <a-col :span="8">
            <a-checkbox value="rMileage">
              {{$t('remainingMileage')}}
            </a-checkbox>
          </a-col> -->
          <a-col :span="8">
            <a-checkbox value="plate">
              {{$t('plateNumber')}}
            </a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </div>

  </div>
</template>

<i18n>
  {
    "zh-CN": {
      "businessData": "营业数据",
      "ebikeInfo":"车辆信息",
      "powerkwh": "电量(kWh)",
      "powerper": "电量(%)",
      "voltage": "电压(V)",
      "electricCurrent": "电流(A)",
      "remainingMileage": "剩余里程",
      "plateNumber": "车牌号"
    },
    "en-US": {
      "businessData": "Business Data",
      "ebikeInfo":"Electric Bicycle",
      "powerkwh": "Electricity(kWh)",
      "powerper": "Electricity(%)",
      "voltage": "Voltage (V)",
      "electricCurrent": "Current (A)",
      "remainingMileage": "Remaining mileage",
      "plateNumber": "License Plate"
    },
    "fr-FR": {
      "businessData": "Données opérationnelles",
      "ebikeInfo":"Informations sur le véhicule",
      "powerkwh": "Électricité (kWh)",
      "powerper": "Électricité (%)",
      "voltage": "Tension (V)",
      "electricCurrent": "Courant (A)",
      "remainingMileage": "Kilométrage restant",
      "plateNumber": "Plaque d'immatriculation"
    }
  }
</i18n>

<script>
import { httpAction, getAction } from '@/api/manage'
import draggable from 'vuedraggable'
import BizTrends from './components/BizTrends'
import BizRanking from './components/BizRanking'
import { wgs84togcj02 } from 'gps-convert'
import TrackComponent from "./components/VehicleTrack.vue";
import RentalPayAccountModal from '@/views/rental/account/modules/RentalPayAccountModal.vue'
function isScriptAlreadyLoaded(srcCheck) {
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.includes(srcCheck)) {
          return true; // 如果找到匹配的src，返回true
      }
  }
  return false; // 如果没有找到匹配的src，返回false
}
export default {
  components: {
    RentalPayAccountModal,
    draggable,
    BizTrends,
    BizRanking,
    TrackComponent
  },
  data() {
    return {
      timerId: null,
      storeListUrl: "/rental/store/list-no-page",
      storeList: [],
      vehicleListUrl: "/rental/ebike/location-list",
      vehicleList: [],
      mapCenter: {},
      storeMultiMarker: [],
      vehicleMultiMarker: [],
      vehiclePowerLabel: [],
      vehicleCurrentLabel: [],
      vehicleMileageLabel: [],
      vehicleMultiLabel: [],
      vehiceInfoShowValues: ['plate'],
      map: null,
      infoStoreWin: null,
      infoVehicleWin: null,
      loading: false,
      showTrendStats: false,
      showTrade: true,
      showVehiceInfoOpt: false,
      showTrackComponent: false, // 控制轨迹组件显示的标志
      selectedVehiclePath: [], // 选择的车辆轨迹路径,
      selectedCarCode: '', // 选择的车辆编码
      plate: '',// 车牌号
      titleCar: '',
      currentlongitude: 0, //
      currentlatitude: 0, //
    }
  },
  computed: {
  },
  async created() {
    await this.initMap(); //初始化地图
    this.initRegionOption();
    // 在组件创建时启动定时器
    this.startTimer();
  },
  beforeDestroy() {
    // 在组件销毁前清除定时器，避免内存泄漏
    if (this.timerId) {
      clearInterval(this.timerId);
    }
  },
  methods: {
    onChangeShowValues(checkedValue) {
      if (checkedValue.length > 4) {
        this.$message.info('要求选择4个以下选项');
      } else {
        this.vehiceInfoShowValues = checkedValue;
      }
    },
    handleBack() {
      this.$router.go(-1);
    },
    startTimer() {
      // 创建一个定时器，每15秒执行一次
      this.timerId = setInterval(() => {
        this.getVehicleList();
        // 在这里可以添加你想要定时执行的任务
      }, 15000); // 15000 毫秒 = 15 秒
    },
    async loadScript() {
      const KEY = window._CONFIG['qqMapKey'];
      const scriptSrc = `https://map.qq.com/api/gljs?v=1.exp&libraries=tools&key=${KEY}`;
      
      return new Promise((resolve, reject) => {
        if (isScriptAlreadyLoaded(scriptSrc)) {
          console.log('The script has already been loaded.');
          resolve(); // 如果脚本已经加载，则直接解决 Promise
        } else {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src = scriptSrc;
          script.onload = () => {
            console.log('Script loaded successfully.', scriptSrc);
            resolve(); // 脚本加载完成后解决 Promise
          };
          script.onerror = (error) => {
            console.error('Error loading script:', error);
            reject(error); // 脚本加载出错时拒绝 Promise
          };
          document.body.appendChild(script);
        }
      });
    },
    async initMap() {
      await this.loadScript();
      if(!this.map){
         // 初始化地图
        const center = new TMap.LatLng(39.98210863924864, 116.31310899739151);
        this.map = new TMap.Map('container', {
          zoom: 12, // 设置地图缩放级别
          center: center, // 设置地图中心点坐标
        });
        this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE);
        this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);
        this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION);
      }
      // this.initStoreInfoWin();
      // this.initVehicleInfoWin();
    },
    async initRegionOption() {
      await this.getStoreList();
      await this.getVehicleList();
      // 计算所有标记的边界
      var bounds = new TMap.LatLngBounds();
      this.vehicleMultiMarker.forEach((marker)=> {
        marker.geometries.forEach(geometry => {
          bounds.extend(new TMap.LatLng(geometry.position.lat, geometry.position.lng));
        });
      });
       // 调整地图视图以包含所有标记
      this.map.fitBounds(bounds);
    },
    async getStoreList() {
      const res = await getAction(this.storeListUrl);
      if (res.success) {
        this.storeList = res.result;
        this.initStoreMarker();
      }
    },
    initStoreMarker() {
      let geos = [];
      for (let i = 0; i < this.storeList.length; i++) {
        const storeItem = this.storeList[i];
        const geoItem = {
          "id": "store_" + storeItem.id,
          "styleId": 'marker',
          "position": new TMap.LatLng(storeItem.latitude, storeItem.longitude),
          "properties": {
            "title": storeItem.meshPointsName
          }
        }
        geos.push(geoItem);
      }
      var imageUrl = '/site.png'; // 注意：这里使用的是绝对路径（相对于 public 文件夹）
      const storeMarkerId = '_store-marker-layer';
      var marker = this.storeMultiMarker.find(item => item.id == storeMarkerId);
      this.storeMultiMarker.forEach(item => {
        if (item.id != storeMarkerId) {
          item.setVisible(false);
        }
      })
      if (!marker) {
        marker = new TMap.MultiMarker({
          id: storeMarkerId,
          map: this.map,
          styles: {
            "marker": new TMap.MarkerStyle({
              "width": 24,
              "height": 35,
              "anchor": { x: 12, y: 35 },
              "src": imageUrl
            })
          },
          geometries: geos
        });
        this.storeMultiMarker.push(marker);
      } else {
        marker.setGeometries(geos);
        marker.setVisible(true);
      }

      //监听标注点击事件
      marker.on("click", (evt) => {
        // this.infoStoreWin.setPosition(evt.geometry.position);//设置信息窗位置
        // this.infoStoreWin.setContent(evt.geometry.properties.title);//设置信息窗内容
        // this.infoStoreWin.open(); //打开信息窗
      })
    },
    async getVehicleList() {
      const res = await getAction(this.vehicleListUrl);
      if (res.success) {
        this.vehicleList = res.result;
        this.initVehiclePoint();
      }
    },
    modalFormOk() {
      this.showTrackComponent = false;
    },
    modalFormCancel() {
      this.showTrackComponent = false;
    },
    initVehiclePoint() {
      if (this.vehicleList) {
        let vehicleMarkerGeos = []; //车辆标注
        let powerLabelGeos = [];    //电量标签(电量，电量百分比，电压)
        let currentLabelGeos = [];  //电流标签（电流，预估里程）

        for (let i = 0; i < this.vehicleList.length; i++) {
          const vehicleItem = this.vehicleList[i];
          const lngLat = wgs84togcj02([vehicleItem.longitude, vehicleItem.latitude])
          //车辆标注
          const markerGeoItem = {
            "id": "vehicle_marker" + vehicleItem.carCode,
            "styleId": vehicleItem.status ? 'marker' + vehicleItem.status : 'marker1',
            "position": new TMap.LatLng(lngLat[1], lngLat[0]),
            "properties": {
              "title": vehicleItem.carCode
            }
          }
          vehicleMarkerGeos.push(markerGeoItem);

          //电量标签
          let powerLabelContent = "";
          if (this.vehiceInfoShowValues.indexOf("rpow") != -1) {
            const rpow = (typeof vehicleItem.rpow === 'number') ? (vehicleItem.rpow / 1000).toFixed(3) : 'N/A ';
            powerLabelContent = powerLabelContent + rpow + " ";
          }
          if (this.vehiceInfoShowValues.indexOf("rpowCap") != -1) {
            const rpowCap = (typeof vehicleItem.rpowCap === 'number') ? vehicleItem.rpowCap : 'N/A ';
            powerLabelContent = powerLabelContent + rpowCap + "% ";
          }
          if (this.vehiceInfoShowValues.indexOf("voltage") != -1) {
            const voltage = (typeof vehicleItem.voltage === 'number') ? (vehicleItem.voltage).toFixed(1) : 'N/A ';
            powerLabelContent = powerLabelContent + voltage + "V ";
          }
          if (this.vehiceInfoShowValues.indexOf("plate") != -1) {
            const plate = vehicleItem.plate;
            powerLabelContent = powerLabelContent + plate;
          }

          const powerLabelGeoItem = {
            "id": "vehicle_power_label_" + vehicleItem.carCode,
            "styleId": 'label',
            "position": new TMap.LatLng(lngLat[1], lngLat[0]),
            "content": powerLabelContent, // 标注文本
            "properties": {
              "title": vehicleItem.carCode
            }
          }
          powerLabelGeos.push(powerLabelGeoItem);

          //电流标签
          let currentLabelContent = "";
          if (this.vehiceInfoShowValues.indexOf("current") != -1) {
            const current = (typeof vehicleItem.current === 'number') ? (vehicleItem.current).toFixed(2) : 'N/A ';
            currentLabelContent = currentLabelContent + current + "A ";
            //currentLabelContent = currentLabelContent + (vehicleItem.current).toFixed(2) + "A ";
          }
          if (this.vehiceInfoShowValues.indexOf("rMileage") != -1) {
            const rmileage = (typeof vehicleItem.rmileage === 'number') ? vehicleItem.rmileage : 'N/A ';
            currentLabelContent = currentLabelContent + rmileage + "KM ";
          }
          const currentLabelGeoItem = {
            "id": "vehicle_current_label_" + vehicleItem.carCode,
            "styleId": 'label',
            "position": new TMap.LatLng(lngLat[1], lngLat[0]),
            "content": currentLabelContent, // 标注文本
            "properties": {
              "title": vehicleItem.carCode
            }
          }
          currentLabelGeos.push(currentLabelGeoItem);
        }

        //车辆标注图层id
        const vehicleMarkerId = '_vehicle-marker-layer';
        this.drawVehicleMarker(vehicleMarkerId, vehicleMarkerGeos);

        //电量标签图层id
        const vehiclePowerLabeId = '_vehicle-power-label-layer';
        this.drawVehiclePowerLabel(vehiclePowerLabeId, powerLabelGeos);

        //电流标签图层id
        const vehicleCurrentLabeId = '_vehicle-current-label-layer';
        this.drawVehicleCurrentLabel(vehicleCurrentLabeId, currentLabelGeos);
        // 添加车辆点击事件监听器
        this.vehicleMultiMarker.forEach(marker => {
          marker.on("click", (evt) => {
            const clickedVehicle = this.vehicleList.find(vehicle => vehicle.carCode === evt.geometry.properties.title);
            if (clickedVehicle) {
              // 设置轨迹路径
              this.selectedCarCode = clickedVehicle.carCode; // 设置选中的车辆编码
              this.plate = clickedVehicle.plate; // 设置选中的车牌号
              this.currentlongitude = clickedVehicle.longitude; //
              this.currentlatitude = clickedVehicle.latitude; //

              this.showTrackComponent = true;
              const carCodeLast4 = clickedVehicle.carCode.slice(-4);
              const combinedStr = `${clickedVehicle.plate}-${carCodeLast4}`;
              this.titleCar = combinedStr;

              /* this.$nextTick(()=>{
                  //this.$refs.modalForm.showModal();
                  //this.$refs.modalForm.getTrackList(clickedVehicle.carCode);
                })*/

            }
          });
        });

      }
    },
    addVehicleMarker(vehicleMarkerId, geometries) {
      const imageUrl1 = '/vehicle1.png';
      const imageUrl2 = '/vehicle2.png';
      const imageUrl3 = '/vehicle3.png';
      const marker = new TMap.MultiMarker({
        id: vehicleMarkerId,
        map: this.map,
        styles: {
          "marker1": new TMap.MarkerStyle({
            "width": 24,
            "height": 35,
            "anchor": { x: 12, y: 35 },
            "src": imageUrl1
          }),
          "marker2": new TMap.MarkerStyle({
            "width": 24,
            "height": 35,
            "anchor": { x: 12, y: 35 },
            "src": imageUrl2
          }),
          "marker3": new TMap.MarkerStyle({
            "width": 24,
            "height": 35,
            "anchor": { x: 12, y: 35 },
            "src": imageUrl3
          })
        },
        geometries: geometries
      });
      return marker;
    },
    drawVehicleMarker(vehicleMarkerId, vehicleMarkerGeos) {
      //隐藏其他车辆标注图层
      this.vehicleMultiMarker.forEach(item => {
        if (item.id != vehicleMarkerId) {
          item.setVisible(false);
        }
      })
      // 获取当前图层，如果没有新增图层
      var marker = this.vehicleMultiMarker.find(item => item.id == vehicleMarkerId);
      if (!marker) {
        marker = this.addVehicleMarker(vehicleMarkerId, vehicleMarkerGeos)
        this.vehicleMultiMarker.push(marker);
      } else {
        marker.setGeometries(vehicleMarkerGeos);
        marker.setVisible(true);
      }
    },
    addVehicleLabel(vehicleLabeId, offset, geometries) {
      const label = new TMap.MultiLabel({
        id: vehicleLabeId,
        map: this.map,
        styles: {
          "label": new TMap.LabelStyle({
            color: '#ff0000', // 颜色属性
            size: 8, // 文字大小属性
            offset: offset, // 文字偏移属性单位为像素
            angle: 0, // 文字旋转属性
            alignment: 'center', // 文字水平对齐属性
            verticalAlignment: 'middle', // 文字垂直对齐属性
          }),
        },
        geometries: geometries
      });
      return label;
    },
    drawVehiclePowerLabel(vehiclePowerLabeId, powerLabelGeos) {
      //隐藏其他电量标签图层
      this.vehiclePowerLabel.forEach(item => {
        if (item.id != vehiclePowerLabeId) {
          item.setVisible(false);
        }
      })
      // 获取当前图层，如果没有新增图层
      var powerLabel = this.vehiclePowerLabel.find(item => item.id == vehiclePowerLabeId);
      if (!powerLabel) {
        powerLabel = this.addVehicleLabel(vehiclePowerLabeId, { x: 0, y: -60 }, powerLabelGeos)
        this.vehiclePowerLabel.push(powerLabel);
      } else {
        powerLabel.setGeometries(powerLabelGeos);
        powerLabel.setVisible(true);
      }
    },
    drawVehicleCurrentLabel(vehicleCurrentLabeId, currentLabelGeos) {
      //隐藏其他电量标签图层
      this.vehicleCurrentLabel.forEach(item => {
        if (item.id != vehicleCurrentLabeId) {
          item.setVisible(false);
        }
      })
      // 获取当前图层，如果没有新增图层
      var currentLabel = this.vehicleCurrentLabel.find(item => item.id == vehicleCurrentLabeId);
      if (!currentLabel) {
        currentLabel = this.addVehicleLabel(vehicleCurrentLabeId, { x: 0, y: -60 }, currentLabelGeos)
        this.vehicleCurrentLabel.push(currentLabel);
      } else {
        currentLabel.setGeometries(currentLabelGeos);
        currentLabel.setVisible(true);
      }
    }

  }
}
</script>


<style>
.vehicle-win {
  height: 90px;
  width: 320px;
  box-shadow: 0px 2px 10px -2px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  padding: 10px;
  color: #000;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  /* position: fixed;
        z-index: 9999;
        right: 20px;
        top: 200px; */
}

.vehicle-win__item {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.vehicle-win__power {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 10px;
}

.vehicle-win__code {}

.vehicle-win__name {
  font-size: 33px;
}

.vehicle-win__status {}
</style>
<style scoped lang="less">
.srceen-wrapper {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  position: relative;

  .nav-bar {
    position: absolute;
    right: 20px;
    top: 20px;
    z-index: 1000;

    .nav-icon {
      font-size: 66px;
      color: #fff;
    }
  }

  .container {
    width: 100vw;
    height: 100vh;
  }

  .query-bar {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1000;
  }

  /*选中样式*/
  .chosen {
    border: solid 2px #3089dc !important;
  }

  .trend-stats-card {
    max-width: 460px;
    width: calc(100% - 40px);
    top: 160px;
    left: 20px;
    position: absolute;
    z-index: 1000;
  }

  .site-ranking-card {
    max-width: 460px;
    width: calc(100% - 40px);
    top: 220px;
    left: 20px;
    position: absolute;
    z-index: 1000;
  }

  .vehicle-ranking-card {
    max-width: 460px;
    width: calc(100% - 40px);
    top: 280px;
    left: 20px;
    position: absolute;
    z-index: 1000;
  }

  .trade-card {
    height: 90px;
    width: 220px;
    box-shadow: 0px 2px 10px -2px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    padding: 10px 0;
    color: #000;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    z-index: 1000;
    right: 20px;

    &:hover {
      cursor: pointer;
      box-shadow: 0px 4px 20px -4px rgba(0, 0, 0, 0.5);
    }

    .trade-card__title {
      font-size: 12px;
    }

    .trade-card__total {
      .trade-card__total_num {
        font-size: 26px;
      }

      .trade-card__total_unit {
        font-size: 12px;
      }
    }

    .trade-card__info {
      font-size: 12px;
      display: flex;
      justify-content: center;

      .trade-card__info_name {}

      .trade-card__info_num {
        margin: 0 0.5em;
      }

      .trade-card__info_unit {}
    }
  }

  .vehicleinfo-opt-card {
    max-width: 460px;
    width: calc(100% - 40px);
    top: 340px;
    left: 20px;
    position: absolute;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    background-color: #fff;
    padding: 20px;
  }

}
</style>